<?php

namespace addons\qingdongams\model;

use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 *零件表
 */
class Parts Extends Model
{
	use SoftDelete;


    protected $name = 'qingdongams_parts';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    public function staff(){
		return $this->hasOne(Staff::class, 'id', 'staff_id')->field('id,name,img');
	}

	//创建人
	public function createStaff() {
		return $this->hasOne(Staff::class, 'id', 'create_staff_id')->field('id,name,img');
	}


    public function getImgAttr($value) {
        if ($value) {
            return cdnurl(File::getUrl($value), true);
        } else {
            return $value;
        }
    }
    //获取产品
    public function getProductIdAttr($value) {
        $value=explode(',',$value);
        $names=Product::where(['id'=>['in',$value]])->column('name');
        return implode(',',$names);
    }


	//创建零件
	public static function createParts($params) {

		$staff = Staff::info();
		if (!empty($staff)) {
			$params['create_staff_id'] = $staff->id;
			$params['update_staff_id'] = $staff->id;
		}
		$customer              = new self;
		// 调用当前模型对应的User验证器类进行数据验证
		$result = $customer->allowField(true)->save($params);
		$lastId = $customer->getLastInsID();
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($customer->getError());
		}


		return $lastId;
	}


	/**
	 *修改零件信息
	 */
	public static function updateParts($params) {

		$customer = new self;
		// 调用当前模型对应的User验证器类进行数据验证
		$result = $customer->save($params, ['id' => $params['id']]);
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($customer->getError());
		}


		return true;
	}
}
